import 'package:card_swiper/card_swiper.dart';
import 'package:chat_app_project/models/const.dart';
import 'package:chat_app_project/models/demand_entity.dart';
import 'package:chat_app_project/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:getwidget/components/button/gf_button.dart';
import 'package:wukongimfluttersdk/entity/channel.dart';
import 'package:wukongimfluttersdk/type/const.dart';
import 'package:wukongimfluttersdk/wkim.dart';

import '../../../constants.dart';
import '../../../dao/follow_dao.dart';
import '../../../dao/im_dao.dart';
import '../../../models/res_entity.dart';
import '../../messages/message_screen.dart';
import 'item_widget.dart';

class DemandDetail extends StatefulWidget {
  const DemandDetail({Key? key, required this.demandEntity}) : super(key: key);

  final DemandEntity demandEntity;

  @override
  State<DemandDetail> createState() => _DemandDetailState();
}

class _DemandDetailState extends State<DemandDetail> {
  late DemandEntity demandEntity;

  @override
  void initState() {
    super.initState();
    demandEntity = widget.demandEntity;
    demandEntity.pics.add(demandEntity.pics.first);
    demandEntity.pics.add(demandEntity.pics.first);
    demandEntity.pics.add(demandEntity.pics.first);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(),
      body: Padding(
        padding: const EdgeInsets.all(2.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.all(10.0),
              child: Row(
                children: [
                  CircleAvatar(
                    backgroundImage:
                        NetworkImage(demandEntity.memberInfo.avatar),
                  ),
                  SizedBox(width: kDefaultPadding * 0.5),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(demandEntity.memberInfo.nickName,
                          style: TextStyle(fontSize: 16)),
                      // Text('Active 3m ago', style: TextStyle(fontSize: 12))
                    ],
                  ),
                  if (UserInfo.uid != demandEntity.memberInfo.id.toString())
                    GFButton(
                      child: const Text("关注"),
                      onPressed: () {
                        FollowDao.follow(demandEntity.memberInfo.id.toString()).then((value){
                          if (value.success) {
                            ToastUtil.toast("关注成功");
                          } else {
                            ToastUtil.toast("关注失败");
                          }
                        });
                      },
                    ),
                  if (UserInfo.uid != demandEntity.memberInfo.id.toString())
                    GFButton(
                      child: const Text("私聊"),
                      onPressed: () {
                        var channelID = demandEntity.memberInfo.id.toString();
                        var channelType = WKChannelType.personal;
                        WKChannel wkChannel = WKChannel(channelID, channelType);
                        ImDao.getChannelInfo({
                          "channel_id": channelID,
                          "channel_type": channelType
                        }).then((value) {
                          var data = value.data;
                          wkChannel.avatar = data["avatar"];
                          wkChannel.channelName = data["channelName"] ?? "";
                          wkChannel.channelRemark = data["channelRemark"] ?? "";
                          //更新本地channel资料
                          // 获取到资料后 通过back返回
                          WKIM.shared.channelManager
                              .addOrUpdateChannel(wkChannel);
                          //跳转到聊天详情
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              // builder: (context) => const ChatPage(),
                              builder: (context) => MessagesScreen(
                                currentChannel: wkChannel,
                              ),
                            ),
                          );
                        });
                      },
                    ),
                ],
              ),
            ),
            SizedBox(
              height: MediaQuery.of(context).size.height / 2.5,
              child: Swiper(
                itemBuilder: (BuildContext context, int index) {
                  return Image.network(
                    demandEntity.pics[index],
                    fit: BoxFit.fitWidth,
                  );
                },
                itemCount: demandEntity.pics.length,
                pagination:
                    const SwiperPagination(builder: SwiperPagination.rect),
                // control: const SwiperControl(),
              ),
            ),
            Text(demandEntity.content),
            _buildContentWidget()
          ],
        ),
      ),
    );
  }

  AppBar buildAppBar() {
    return AppBar(
      titleSpacing: 0,
      automaticallyImplyLeading: true,
      actions: [
        IconButton(
          icon: const Icon(Icons.more_horiz),
          onPressed: () {},
        ),
        IconButton(
          icon: const Icon(Icons.share),
          onPressed: () {},
        ),
      ],
    );
  }

  Widget _buildContentWidget() {
    return Expanded(
      child: Column(
        children: [
          _buildListWidget(),
          _buildInputWidget(),
        ],
      ),
    );
  }

  Widget _buildListWidget() {
    return Expanded(
      child: MediaQuery.removePadding(
        removeTop: true,
        context: context,
        child: ListView.separated(
          controller: ScrollController(),
          itemCount: 10,
          itemBuilder: (context, index) => _buildItem(index),
          separatorBuilder: (context, index) =>
              Container(height: 8, color: const Color(0xfff5f5f5)),
        ),
      ),
    );
  }

  final TextEditingController _textEditingController = TextEditingController();
  final FocusNode _focusNode = FocusNode();

  Widget _buildInputWidget() {
    return SafeArea(
        child: Row(
      children: [
        const SizedBox(width: kDefaultPadding / 2),
        Expanded(
          child: Container(
            padding:
                const EdgeInsets.symmetric(horizontal: kDefaultPadding * 0.5),
            decoration: BoxDecoration(
              color: kPrimaryColor.withOpacity(0.07),
              borderRadius: BorderRadius.circular(40),
            ),
            child: Row(
              children: [
                const SizedBox(width: kDefaultPadding / 2),
                Expanded(
                  child: TextField(
                    focusNode: _focusNode,
                    onChanged: (v) {
                      setState(() {});
                    },
                    onTap: () {
                      setState(() {});
                    },
                    //点击其他地方隐藏键盘
                    // onTapOutside: (p) {
                    //   print("${p.position}");
                    //   // if (_focusNode.hasFocus) {
                    //   //   _focusNode.unfocus();
                    //   // }
                    //   setState(() {});
                    // },
                    controller: _textEditingController,
                    autofocus: false,
                    decoration: const InputDecoration(
                        border: InputBorder.none, hintText: '说点什么吧...'),
                  ),
                ),
                const SizedBox(width: kDefaultPadding / 4),
              ],
            ),
          ),
        ),
        GFButton(
          // horizontalPadding: 0,
          // mainButtonName: '发送',
          text: "发送",
          onPressed: () {
            if (_textEditingController.text != '') {
              _textEditingController.text = '';
            }
          },
        ),
        const SizedBox(width: kDefaultPadding / 2),
      ],
    ));
  }

  Widget _buildItem(int index) {
    return CommentItemWidget(
      index: index,
      onClickItem: (index) {
        // this.index = index;
        // setShowInput(true);
      },
      // onClickReply: (index) => _toDetailPage(index),
    );
  }
}
